package com.cm.sys.intermanager.service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.cm.sys.intermanager.utils.LogEncoder;

/**
*@Date 2020/2/27
*@Author 蒋红星，郭兆鹏
*作用: Websocket服务端设计
*/
@Component
@ServerEndpoint(value = "/websocket/{wsId}", encoders = {LogEncoder.class})
public class WebSocketServer {

    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    //这个不需要了，记录登陆数直接拿集合大小去，避免同一用户多次登录
//    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    private Session session;   //这个session要保存在外部，否则每次都是用一个session
    private String wsId;

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    private static Map<String,WebSocketServer> usersMap = new ConcurrentHashMap<>();

    /**
     * 连接时调用的方法
     * @param session
     * @param
     */
    @OnOpen
    public void OnOpen(Session session, @PathParam("wsId") String wsId){
        logger.info("新客户端连入");
        this.session = session; //初始化当前ws实例中的session会话
        this.wsId = wsId;  //初始化当前ws实例中的wsId属性

        usersMap.put(wsId,this);
        //打印，需删除 --------------------
        for (String s : usersMap.keySet()) {
            logger.info("当前用户组：id = "+s+" session="+usersMap.get(s));
        }
        //-------------------------------
        try {
            sendMsg("连接成功",session);
        } catch (IOException e) {
            logger.error("websocket IO异常");
        }
        logger.info("有一个客户端已经连接上");
    }

    /**
     * 关闭连接时调用
     *
     * @param
     */
    @OnClose
    public void OnClose(){
        logger.info("一个客户端关闭连接");
        usersMap.remove(this.wsId);
        //打印，需删除 --------------------
        for (String s : usersMap.keySet()) {
            logger.info("当前用户组：id = "+s+" session="+usersMap.get(s));
        }
        //-------------------------------
    }

    /**
     * @param msg
     */
    @OnMessage
    public void OnMessage(String msg) {
        System.out.println("接收到客户端传来的： " + msg);
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误", error);
    }

    /**
     * 发送消息格式为json
     *
     * @param logs
     * @throws IOException
     * @throws EncodeException 
     */
    public void sendMsg(List<Map<String, String>> logs) throws EncodeException, IOException {
        synchronized (this.session){
            for (Map map:logs) {
                this.session.getBasicRemote().sendObject(map);
            }
        }
    }

    /**
     * 发送消息，字符串消息
     *
     * @param msg
     * @throws IOException
     * @throws EncodeException
     */
    public void sendMsg(String msg,Session session) throws IOException {
            session.getBasicRemote().sendText(msg);
    }


    /**
     * 根据采集层传递过来的参数进行推送测试
     */
    public void sendInfo(List<Map<String, String>> logs){
//        for (Map<String, String> log : logs) {
//            String wsId = log.get("wsId");
//            for (String wskey : usersMap.keySet()) {
//                if(wskey.equals(wsId)){
//                    usersMap.get(wskey).sendMsg(log.get("message"));
//                }
//            }
//        }
    }

//    public static synchronized int getOnlineCount() {
//        return OnlineCount.get();
//    }

//    public static synchronized void addOnlineCount() {
//        OnlineCount.incrementAndGet(); // 在线数加1
//    }
//
//    public static synchronized void subOnlineCount() {
//        OnlineCount.decrementAndGet(); // 在线数加1
//    }

    public static synchronized Map<String, WebSocketServer> getWebSocketMap() {
       return usersMap;
    }
}
